package cn.sdhuijin.healthexam.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import cn.sdhuijin.healthexam.ExitApplication;
import cn.sdhuijin.healthexam.R;
import cn.sdhuijin.healthexam.control.AbstractControlActivity;
import cn.sdhuijin.healthexam.util.Util;

/**
 * 系统升级设置
 * 
 * 修改完成
 * 
 * @author sunping
 */
public class UpdateActivity extends AbstractControlActivity implements
		OnClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update);
		ExitApplication.getInstance().addActivity(this);

		addEditTextView(R.id.edt_update_url, "检测网址");
		addEditTextView(R.id.edt_update_cycle, "检测周期");

		setUpdateFileDefault();
		enableButton();
		controlManager.setPropertiesPath(Environment
				.getExternalStorageDirectory() + "/health/update.txt");
		Log.i(this.getClass().getSimpleName(),
				"文件路径： " + Environment.getExternalStorageDirectory()
						+ "/health/update.txt");
		controlManager.toControl();

		this.setButtonListener(this, R.id.btn_back, R.id.btn_update,
				R.id.btn_save);
	}

	public void enableButton() {
		new Thread() {
			public void run() {
				Properties properties = new Properties();
				try {
					File file = new File(
							Environment.getExternalStorageDirectory()
									+ "/health/update.txt");
					Log.i(this.getClass().getSimpleName(),
							"路径1" + file.getAbsolutePath());
					properties.load(new FileReader(file.getAbsolutePath()));
					String updateUrl = properties.getProperty("检测网址");
					Log.i(this.getClass().getSimpleName(), "检测网址" + updateUrl);
					if (Util.allIsNotEmpty(updateUrl)) {
						String ver = Util.sendHttpGet(
								updateUrl + "version.txt", "v=" + Util.version);
						Log.e("Version", ver);
						Log.e("Versio1n", Util.version);
						if (Util.isNetAvailable(UpdateActivity.this)
								&& Util.allIsNotEmpty(ver)
								&& !ver.trim().equals(Util.version)) {
							Log.e("按钮", "可用");
							UpdateActivity.this.findViewById(R.id.btn_update)
									.setEnabled(true);
						} else {
							Log.e("按钮", "禁用");
							UpdateActivity.this.findViewById(R.id.btn_update)
									.setEnabled(false);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 保存更新设置
	 * 
	 */
	private void saveUpdateSetting() {
		String updateUrl = this.getControlValue(R.id.edt_update_url); // 检测网址
		String updateCycle = this.getControlValue(R.id.edt_update_cycle); // 检测周期
		if (Util.allIsNotEmpty(updateUrl, updateCycle)) {
			if (isHomepage(updateUrl)) {
				controlManager.toProperties();
				this.toastInformation(R.string.update_setting_success);
			} else {
				this.toastInformation(R.string.input_error);
			}

		} else {
			this.toastInformation(R.string.setting_not_null);
		}
	}

	/**
	 * @param 待验证的字符串
	 * @return 如果是符合网址格式的字符串,返回<b>true</b>,否则为<b>false</b>
	 */
	public static boolean isHomepage(String str) {
		String regex = "^((https|http|ftp|rtsp|mms)?://)"
				+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@
				+ "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
				+ "|" // 允许IP和DOMAIN（域名）
				+ "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
				+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
				+ "[a-z]{2,6})" // first level domain- .com or .museum
				+ "(:[0-9]{1,4})?" // 端口- :80
				+ "((/?)|" // a slash isn't required if there is no file name
				+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
		return match(regex, str);
	}

	/**
	 * @param regex
	 *            正则表达式字符串
	 * @param str
	 *            要匹配的字符串
	 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
	 */
	private static boolean match(String regex, String str) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	/**
	 * 系统更新
	 */
	private void update() {
		Properties properties = new Properties();
		try {
			File file = new File(Environment.getExternalStorageDirectory()
					+ "/health/update.txt");
			Log.i(this.getClass().getSimpleName(),
					"路径" + file.getAbsolutePath());
			properties.load(new FileReader(file.getAbsolutePath()));
			String updateUrl = properties.getProperty("检测网址");
			if (Util.allIsNotEmpty(updateUrl)) {
				if (Util.isNetAvailable(this)) {
					Util.update(this.getBaseContext(), updateUrl);
				} else {
					this.toastInformation(R.string.net_is_not_avilable);
				}
			} else {
				this.toastInformation(R.string.update_url_not_set);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 若系统更新参数所保存的文件不存在，则新建文件，写入默认参数
	 */
	private void setUpdateFileDefault() {
		Properties properties = null;
		File file = null;
		File dirFile = null;
		try {
			properties = new Properties();
			dirFile = new File(Environment.getExternalStorageDirectory()
					+ "/health/");
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			file = new File(Environment.getExternalStorageDirectory()
					+ "/health/update.txt");
			if (!file.exists()) {
				file.createNewFile();
				saveUpdateSetting(file, properties);
			} else {
				properties.load(new FileInputStream(file));
				String updateUrl = properties.getProperty("检测网址");
				if (!Util.allIsNotEmpty(updateUrl)) {
					saveUpdateSetting(file, properties);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 保存默认设置
	 * 
	 * @param file
	 * @param properties
	 * @throws Exception
	 */
	private void saveUpdateSetting(File file, Properties properties)
			throws Exception {
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;
		fileInputStream = new FileInputStream(file);
		properties.load(fileInputStream);
		// 检测网址
		properties.setProperty("检测网址", "http://huijin.qiniudn.com/healthexam/");
		// 检测周期
		properties.setProperty("检测周期", "1");
		fileOutputStream = new FileOutputStream(
				Environment.getExternalStorageDirectory()
						+ "/health/update.txt");
		// 保存
		properties.store(fileOutputStream, "系统更新设置参数信息");
	}

	@Override
	public void onClick(View v) {
		int clickId = (Integer) v.getId();
		switch (clickId) {
		case R.id.btn_save:
			saveUpdateSetting();
			break;
		case R.id.btn_update:
			update();
			break;
		case R.id.btn_back:
			finish();
			break;
		}
	}
}
